<?php
namespace core;

class Controller
{
    /**
     * @var string 模块名
     */
    protected $module;
    /**
     * @var string 控制器
     */
    protected $controller;
    /**
     * @var string 方法名
     */
    protected $action;
    /**
     * @var string 模板数据
     */
    protected $data = [];
    /**
     * @var string 视图文件
     */
    private $temp;

    /**
     * 构造方法
     * @author sweeterstar<2021-04-25>
     * @param string $module
     * @param string $controller
     * @param string $action
     */
    function __construct($module, $controller, $action)
    {
        $this->module     = $module;
        $this->controller = $controller;
        $this->action     = $action;
        $this->temp       = TEMP_PATH;
    }

    /**
     * @author sweeterstar<2021-04-25>
     * @param  string|array $key
     * @param  string $value
     * @return [type]
     */
    public function assign($key, $value = '')
    {
        if (is_string($key)) {
            $this->data[$key] = $value;
        } else if (is_array($key)) {
            $this->data = array_merge($this->data, $key);
        }
    }

    /**
     * @author sweeterstar<2021-04-25>
     * @param string $file 模板文件
     * @param array $vars 模板变量
     * @return [type]
     */
    public function fetch($template = '', $vars = [])
    {
        if ($vars) {
            $this->data = array_merge($this->data, $vars);
        }

        if (strpos($template, '.')) {
            $template = str_replace('.', DS, $template);
        }

        if ('' == $template) {
            $template = $this->module . DS . $this->controller . DS . $this->action;
        }

        // 处理大小写，驼峰式方法名
        $template = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', trim($template, DS)));

        $template = $this->temp . $template . EXT;

        if (is_file($template)) {
            // 变量分解独立
            $this->data and extract($this->data, EXTR_OVERWRITE);
            
            // 页面缓存
            ob_start();
            ob_implicit_flush(0);

            // 获取模板内容
            $content = file_get_contents($template);

            // 获取并清空缓存
            $content = ob_get_clean();

            include $template;
        } else {
            die(sprintf('[ Error ] template file not exists: %s', $template));
            // throw new \Exception('template file not exists:' . $template);
        }
    }
}